// shell script with shelljs
import shell from "shelljs";
import path from "path";
import generateRSDatamodel from "./generateRSDatamodel";
import fetch from "node-fetch";
import { getEnvPrismaUrl, getPrismaUrl, setEnvironments } from "./setup";

const deploy = async () => {

	try {
		shell.echo("\nDeploying the dependent services in docker containers...\n");

		generateRSDatamodel();

		shell.cd(path.join(__dirname, "..", "database"));

		const envs = setEnvironments();
		shell.exec(`${envs} docker-compose -p repchain-block-courier up -d`);

		shell.echo("\nWaiting the containers to be working...\n");

		const waitContainerServerWorking = async (name, url) => {
			let alreadyWorking = false;
			while (!alreadyWorking) {
				try {
					const res = await fetch(url, { timeout: 3000 });
					alreadyWorking = (res.status === 200);
				} catch (e) {
					if (e.code === "ECONNRESET" || e.code === "ECONNREFUSED" || e.code === "ETIMEOUT") continue;
					console.error(`Failed to fetch ${name} server from the container at '${url}'`, e);
					throw e;
				};
			}
		}

		await waitContainerServerWorking("prisma1", getPrismaUrl());

		shell.echo("The containers are working now!\n");
		const force = process.argv[2];
		const envPrismaUrl = getEnvPrismaUrl();
		shell.echo("Deploying the graphql schema to the prisma1 server (need some minutes)...\n");
		shell.exec(`${envPrismaUrl} npx prisma1 deploy ${force}`, { silent: false });
		shell.echo("Deployed the graphql schema to prisma1 server!\n");
	} catch (e) {
		console.error(e);
	}
}

deploy();
